package com.rajaev.dtu.tractor.infrastructure.interceptors;


import com.rajaev.dtu.tractor.infrastructure.base.errors.BusinessException;
import com.rajaev.dtu.tractor.infrastructure.base.errors.ErrorCodes;
import com.rajaev.dtu.tractor.infrastructure.helper.SpringEnvHelper;
import com.rajaev.dtu.tractor.infrastructure.security.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.rajaev.dtu.tractor.infrastructure.base.common.Constants.Authorization;
import static com.rajaev.dtu.tractor.infrastructure.base.common.Constants.cacheTokenPrefix;


@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    RedisTemplate redisTemplate;

    @Value("${spring.profiles.active}")
    private String env;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(Authorization);

        //当为option 请求的时候，不判断权限
        if ("options".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        if (!SpringEnvHelper.isProd()) {

            UserContextHolder.setLoginUser("tianjie");

            return true;
        }


        if (redisTemplate.getExpire(cacheTokenPrefix + token) >= 0) {
            redisTemplate.expire(cacheTokenPrefix + token, 30, TimeUnit.MINUTES);
            String loginName = (String) redisTemplate.opsForValue().get(cacheTokenPrefix + request.getHeader(Authorization));
            UserContextHolder.setLoginUser(loginName);
            return true;
        } else {
            throw new BusinessException(ErrorCodes.ERR_USER_AUTHINFO);

        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.removeLoginUser();
    }
}
